package com.hangxiang.approval.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hangxiang.approval.common.IntegerCommon;
import com.hangxiang.approval.common.UserInsertCommon;
import com.hangxiang.approval.common.UserLoginCommon;
import com.hangxiang.approval.common.UserPageCommon;
import com.hangxiang.approval.common.UserUpdateCommon;
import com.hangxiang.approval.dao.RoleDao;
import com.hangxiang.approval.dao.RoleMenuDao;
import com.hangxiang.approval.dao.UserDao;
import com.hangxiang.approval.dao.UserManagerDao;
import com.hangxiang.approval.entity.*;
import com.hangxiang.approval.enums.ResultStatusEnum;
import com.hangxiang.approval.enums.UserStateEnum;
import com.hangxiang.approval.exception.MyException;
import com.hangxiang.approval.service.UserService;
import com.hangxiang.approval.utils.BeanConvertUtils;
import com.hangxiang.approval.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;


/**
 * 用户表(User)表服务实现类
 *
 * @author makejava
 * @since 2020-11-23 16:29:56
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private UserDao userDao;
    @Resource
    private RoleDao roleDao;
    @Resource
    private RoleMenuDao roleMenuDao;
    @Resource
    private UserManagerDao userManagerDao;

    /**
     * 通过ID查询单条数据
     *
     * @param common 主键
     * @return 实例对象
     */
    @Override
    public UserVo queryById(IntegerCommon common) {
        UserVo vo = new UserVo();
        User user = userDao.selectById(common.getValue());
        BeanUtils.copyProperties(user, vo);
        return vo;
    }


    /**
     * 新增数据
     *
     * @param userInsertCommon 实例对象
     * @return 实例对象
     */
    @Override
    public Integer insertUser(UserInsertCommon userInsertCommon) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(User::getPhone,userInsertCommon.getPhone());
        User user = userDao.selectOne(wrapper);
        if (user != null) {
            throw new MyException(ResultStatusEnum.USER_INSERT);
        }
        user = new User();
        BeanUtils.copyProperties(userInsertCommon, user);
        userDao.insert(user);
        return user.getId();
    }

    /**
     * 修改数据
     *
     * @param userUpdateCommon 实例对象
     * @return 实例对象
     */
    @Override
    public Integer updateUser(UserUpdateCommon userUpdateCommon) {
        User user = new User();
        BeanUtils.copyProperties(userUpdateCommon, user);
        userDao.updateById(user);
        return user.getId();
    }

    @Override
    public UserVo userLogin(UserLoginCommon common) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(User::getPhone,common.getPhone()).eq(User::getPassword,common.getPassword());
        User user = userDao.selectOne(wrapper);
        if (user == null){
            throw new MyException(ResultStatusEnum.LOGIN);
        }
        if (user.getIsForbidden().equals(UserStateEnum.FORBIDDEN.getType())){
            throw new MyException(ResultStatusEnum.FORBIDDEN);
        }
        user.setFinallyTime(new Date());
        userDao.updateById(user);
        UserVo vo = new UserVo();
        BeanUtils.copyProperties(user,vo);
        List<RoleMenuVo> roleMenuVoArrayList1=new ArrayList<>();
        List<RoleMenuVo> roleMenuVoArrayList2=new ArrayList<>();
        // 获取所有权限明细
        List<RoleMenu> roleMenus = roleMenuDao.selectList(new QueryWrapper<RoleMenu>().lambda().eq(RoleMenu::getRoleId, user.getId()));
        // 获取前端所有菜单
        List<RoleMenu> collect1 = roleMenus.stream().filter(roleMenu -> roleMenu.getMenuType() == 2).collect(Collectors.toList());
        // 获取前端一级菜单
        Set<RoleMenu> c = collect1.stream().filter(roleMenu -> roleMenu.getFirstId() != null).collect(Collectors.toSet());
        ArrayList<RoleMenu> collect3 = c.stream().collect(
                collectingAndThen(
                        toCollection(() -> new TreeSet<RoleMenu>(comparing(RoleMenu::getFirstId))), ArrayList::new));
        // 获取所有后端菜单
        List<RoleMenu> collect2 = roleMenus.stream().filter(roleMenu -> roleMenu.getMenuType() ==1).collect(Collectors.toList());
        // 获取后端一级菜单
        Set<RoleMenu> co = collect2.stream().filter(roleMenu -> roleMenu.getFirstId() != null).collect(Collectors.toSet());
        ArrayList<RoleMenu> collect5 = co.stream().collect(
                collectingAndThen(
                        toCollection(() -> new TreeSet<RoleMenu>(comparing(RoleMenu::getFirstId))), ArrayList::new));
        // 前端菜单
        for (RoleMenu roleMenu : collect3) {
            RoleMenuVo roleMenuVo1 = new RoleMenuVo();
            roleMenuVo1.setIndex(roleMenu.getFirstId());
            roleMenuVo1.setTitle(roleMenu.getFirstName());
            // 获取当前菜单所有二级菜单
            List<RoleMenu> collect4 = collect1.stream().filter(roleMenu1 -> roleMenu1.getFirstId().equals(roleMenu.getFirstId()) && roleMenu1.getSecondId() != null).collect(Collectors.toList());
            List<Map<String,Object>> maps = new ArrayList<>();
            for (RoleMenu menu : collect4) {
                Map<String,Object> map = new HashMap<>();
                map.put("index",menu.getSecondId());
                map.put("title",menu.getSecondName());
                maps.add(map);
            }
            roleMenuVo1.setSubs(maps);
            roleMenuVoArrayList1.add(roleMenuVo1);
        }

        // 后台菜单
        for (RoleMenu roleMenu : collect5) {
            RoleMenuVo roleMenuVo1 = new RoleMenuVo();
            roleMenuVo1.setIndex(roleMenu.getFirstId());
            roleMenuVo1.setTitle(roleMenu.getFirstName());
            // 获取当前菜单所有二级菜单
            List<RoleMenu> collect4 = collect2.stream().filter(roleMenu1 -> roleMenu1.getFirstId().equals(roleMenu.getFirstId()) && roleMenu1.getSecondId() != null).collect(Collectors.toList());
            List<Map<String,Object>> maps = new ArrayList<>();
            for (RoleMenu menu : collect4) {
                Map<String,Object> map = new HashMap<>();
                map.put("index",menu.getSecondId());
                map.put("title",menu.getSecondName());
                maps.add(map);
            }
            roleMenuVo1.setSubs(maps);
            roleMenuVoArrayList2.add(roleMenuVo1);
        }
        vo.setRoleMenuList(roleMenuVoArrayList2);
        vo.setRoleMenuTwoList(roleMenuVoArrayList1);
        return vo;
    }

    @Override
    public PageInfo selectAllInfo(UserPageCommon common) {
        PageHelper.startPage(common.getPageRow(),common.getPageSize());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda().eq(User::getPhone,common.getPhone());
        if (common.getPhone() != null ){
            queryWrapper.lambda().like(User::getPhone,common.getPhone());
        }
        queryWrapper.lambda().like(User::getIsForbidden,0);
        List<User> users = userDao.selectList(queryWrapper);
        List<UserVo> userVos = BeanConvertUtils.convertListTo(users,UserVo::new);
        userVos.forEach(user -> {
            QueryWrapper<UserManager> wrapper = new QueryWrapper<>();
            List<UserManager> userManagers =userManagerDao.selectList(wrapper.lambda().eq(UserManager::getUserId,user.getId()));
            user.setUserManagerList(userManagers);
        });
        PageInfo info = new PageInfo(userVos);
        return info;
    }

    @Override
    public PageInfo selectUserInfo(UserPageCommon common) {
//        List<TemplateVo> templateList=templateDao.selectAllInfo(common);
//        templateList.forEach(template -> {
//            List<ReviewerVo> reviewerList=reviewerDao.selectListCC(template.getTempId());
//            template.setReviewerVoList(reviewerList);
//        });

        List<User> totalUser=userDao.selectList(new QueryWrapper<User>().lambda().eq(User::getIsForbidden,0));
        PageHelper.startPage(common.getPageRow(),common.getPageSize());
        List<User> user=userDao.selectList(new QueryWrapper<User>().lambda().eq(User::getIsForbidden,0));
        List<UserListVo> listVos=new ArrayList<>();
        user.forEach(user1 -> {
            List<UserManager> userManagers=userManagerDao.selectList(new QueryWrapper<UserManager>().lambda().eq(UserManager::getUserId,user1.getId()));
            UserListVo userVo=new UserListVo();
            userVo.setUserName(user1.getUserName());
            userVo.setPhone(user1.getPhone());
            userVo.setNickName(user1.getNickName());
            userVo.setCreateTime(user1.getCreateTime());
            userVo.setSex(user1.getSex());
            userVo.setId(user1.getId());
            userVo.setIsForbidden(user1.getIsForbidden());
            userVo.setUserManagerList(userManagers);
            if(userManagers!=null&&userManagers.size()!=0){
                userVo.setIsManager(1);
            }
            else
            {
                userVo.setIsManager(0);
            }
            listVos.add(userVo);
        });

        PageInfo info = new PageInfo(listVos);
        info.setTotal(totalUser.size());
        return info;
    }
}